import os.path
import time
from concurrent.futures import ProcessPoolExecutor
def task(name):
    print(f'first-{name}')
    time.sleep(20)
    print(f'last-{name}')
    return f"finished-{name}"
# 第一种方法 使用进程池
if __name__ == "__main__":
    with ProcessPoolExecutor() as excusor:
        future01 = excusor.submit(task,'AA')
        future02 = excusor.submit(task, 'BB')
        print('res01-',future01.result())
        print('res02',future02.result())
        print("tail----")


# 第二种方法 使用线程池
# with ThreadPoolExecutor() as excusor:
#     ress = excusor.map(task,['CC','DD'])
#     for item in ress:
#         print(item)
#     print("tail----")

# 拓展 （利用线程池实现 图片下载的功能）
# from urllib.request import urlopen,Request
# def img_download(url):
#     formatRequest = Request(url,headers={'User-Agent':'Mozilla/5.0'})
#     with urlopen(formatRequest) as file_con:
#         file_data = file_con.read()
#     if not file_data:
#         raise Exception(f'down load error {url}')
#     else:
#         filename = os.path.basename(url)
#         with open(filename,'wb') as myfile:
#             myfile.write(file_data)
#     return f"down load success {url}"
#
# urls = [
#     "https://images.pexels.com/photos/18662958/pexels-photo-18662958.jpeg",
#     "https://images.pexels.com/photos/6981693/pexels-photo-6981693.jpeg"
# ]
# # 创建线程池
# with ThreadPoolExecutor() as threadPool:
#     res = threadPool.map(img_download,urls)
#     for item in res:
#         print(item)